"""为了将一些美妙的语音转换为环绕音，提供一些有用的函数。"""
import numpy as np  
from scipy.io import loadmat  
from scipy.signal import convolve  
import soundfile as sf 

def virtual_surround(sound_path:str,result_path:str=None,source_voice=None,samplerate=None,h_angle=0,v_angle=0,slice_size:int=None,conv_list:list=[(24,0)]):
    """对单声道音频施加虚拟环绕算法，生成立体声音频
    ## 依赖
    import numpy as np  

    from scipy.io import loadmat  

    from scipy.signal import convolve  
    
    import soundfile as sf  
    
    ## 参数

    sound_path: str 音频文件路径
    result_path: str 输出文件路径
    source_voice: np.array 单声道音频数据 (xxx,) 建议采样率44100Hz
    samplerate: int 音频采样率
    h_angle: int 废弃 水平方位角（0~24）
    v_angle: int 废弃 高度度（0~49）
    slice_size: int 分段大小。 若为None，分段大小由滤波器个数由决定
    conv_list: list 滤波器列表，将会逐一循环作用与每一段音频帧[(h1,v1),(h2,v2),...]
    
    ## 返回值
    np.array
        立体声音频数据 (xxx,2)
    """
     # 读取音频
    if source_voice is not None:
        sound_data = source_voice
        sample_rate = samplerate
    else:
        sound_data, sample_rate = sf.read(sound_path) 

    # 加载hrtf参数
    file_path = 'cipic-hrtf-database-master\standard_hrir_database\subject_021\hrir_final.mat' 
    data = loadmat(file_path)
    hrir_l = data['hrir_l']
    hrir_r = data['hrir_r']

    processed_list_l = [] # 存储处理后的音频数据
    processed_list_r = [] # 存储处理后的音频数据
    
    fps_num = sound_data.shape[0] # 音频帧数
    conv_num = len(conv_list) # 滤波器数量
    if slice_size is None:
        slice_size = fps_num //conv_num # 动态设置分段大小
    
    
    slice_num = fps_num // slice_size # 分段数
    remain_fps = fps_num % slice_size # 剩余帧数
    slice_list=[sound_data[i*slice_size:(i+1)*slice_size] for i in range(slice_num)] # 分段音频
    if remain_fps != 0:
        slice_list.append(sound_data[-remain_fps:])
        slice_num += 1

    for i in range(slice_num):# 对每一段音频使用不同的滤波器卷积
        slice_data = slice_list[i] # 音频分段
        h_angle = conv_list[i%conv_num][0] 
        v_angle = conv_list[i%conv_num][1]
        hrir_a = hrir_l[h_angle,v_angle,:]   # 左耳滤波器
        hrir_b = hrir_r[h_angle,v_angle,:]   # 右耳滤波器
        proc_data_l = convolve(slice_data,hrir_a,mode='same') # 左耳卷积
        processed_list_l.append(proc_data_l)
        proc_data_r = convolve(slice_data,hrir_b,mode='same') # 右耳卷积
        processed_list_r.append(proc_data_r)
    processed_list_l = np.concatenate(processed_list_l,axis=0)
    processed_list_r = np.concatenate(processed_list_r,axis=0)
    stereo = np.vstack((processed_list_l,processed_list_r)).T

    if result_path is not None:
        sf.write(result_path, stereo, sample_rate)
    
    return stereo
    
    # sf.write(f'spatial_audio_{h_angle}-{v_angle}.wav', stereo, sample_rate)
    # return stereo



    # # 取方位点的数据
    # hrir_a = hrir_l[h_angle,v_angle,:]
    # hrir_b = hrir_r[h_angle,v_angle,:]  

    # # 卷积
    # overl = convolve(sound_data,hrir_a,mode='same')
    # overr = convolve(sound_data,hrir_b,mode="same")

    # # 合成立体声
    # stereo = np.vstack((overl,overr)).T
    # ## stereo = np.stack((overl,overr), axis=1)

    # if result_path is not None:
    #     sf.write(result_path, stereo, sample_rate)
    #     return stereo

    # sf.write(f'spatial_audio_{h_angle}-{v_angle}.wav', stereo, sample_rate)
    # return stereo

    
    